<?php

/**
 * @package account
 */

class PurchaseAccountSummaryReport extends SS_Report implements PermissionProvider {
	protected $sort = 40;
	
	public function title() {
		return _t('PurchaseAccountSummaryReport.TITLE', 'E-Purchase Transaction Summary Report');
	}
	
	/**
	 * @param Member $member
	 * @return boolean
	 */
	public function canView($member = null) {
		if(!$member && $member !== FALSE) {
			$member = Member::currentUser();
		}
		
		$extended = $this->extendedCan(__FUNCTION__, $member);
		if($extended !== null) return $extended;

        return Permission::check('VIEW_PurchaseAccountSummaryReport');
	}
	
	public function extendedCan($methodName, $member) {
		$results = $this->extend($methodName, $member);
		if($results && is_array($results)) {
			// Remove NULLs
			$results = array_filter($results, function($v) {return !is_null($v);});
			// If there are any non-NULL responses, then return the lowest one of them.
			// If any explicitly deny the permission, then we don't get access 
			if($results) return min($results);
		}
		return null;
	}
	
	public function sourceRecords($params, $sort, $limit) {
		if($sort) {
			$parts = explode(' ', $sort);
			$field = $parts[0];
			$direction = $parts[1];
			
			if($field == 'Name') {
			    $sort = 'FirstName ' . $direction;
			}
		}

		$where = array('Member.IsDistributor = 1');
        if(isset($params['StartDate']) && $params['StartDate']){
        	$where[] = sprintf("DATE(PurchaseAccount.Date) >= '%s'", DBField::create_field('Date', $params['StartDate'])->URLDate());
        }
		
		if(isset($params['EndDate']) && $params['EndDate']){
        	$where[] = sprintf("DATE(PurchaseAccount.Date) <= '%s'", DBField::create_field('Date', $params['EndDate'])->URLDate());
        }
        
        if(isset($params['Username']) && $params['Username']){
        	$where[] = sprintf("Member.Username LIKE '%%%s%%'", $params['Username']);
        }
		
		$query = new SQLQuery();
		$query = $query->setFrom('PurchaseAccount')->setWhere($where)->setOrderBy($sort)->setLimit($limit)->setGroupBy('PurchaseAccount.MemberID')->addInnerJoin('Member', 'PurchaseAccount.MemberID = Member.ID')->selectField('SUM(PurchaseAccount.Debit)', 'Debit')->selectField('SUM(PurchaseAccount.Credit)', 'Credit')->selectField('SUM(PurchaseAccount.Credit - PurchaseAccount.Debit)', 'ForwardBalance');

		$returnSet = new ArrayList();
		foreach($query->execute() as $item){
			$data = new ArrayData($item);
			$returnSet->push($data);
		}

		return $returnSet;
	}

	public function columns() {
		$fields = array(
			'Username' => array(
				'title' => _t('PurchaseAccountSummaryReport.USERNAME', 'Username')
			),
			'Name' => array(
				'title' => _t('PurchaseAccountSummaryReport.NAME', 'Name'),
				'formatting' => function($value, $item) {
				    return Distributor::get_name_by_id($item->MemberID);
                }
			),
			'Credit' => array(
                'title' => _t('PurchaseAccountSummaryReport.IN', 'In'),
                'casting' => 'Decimal->Nice'
            ),
            'Debit' => array(
                'title' => _t('PurchaseAccountSummaryReport.OUT', 'Out'),
                'casting' => 'Decimal->Nice'
            ),
            'ForwardBalance' => array(
                'title' => _t('PurchaseAccountSummaryReport.BALANCE', 'Balance'),
                'casting' => 'Decimal->Nice'
            )
		);
		
		return $fields;
	}
	
	public function parameterFields() {
		return new FieldList(
            FieldGroup::create(
            	DateField::create('filters[StartDate]', '')->addExtraClass('no-change-track'),
				DateField::create('filters[EndDate]', '')->addExtraClass('no-change-track')
			)->setTitle(_t('PurchaseAccountSummaryReport.DATE', 'Date')),
			UsernameField::create('Username', _t('PurchaseAccountSummaryReport.USERNAME', 'Username'))
		);
	}

	public function providePermissions() {
        return array(
            'VIEW_PurchaseAccountSummaryReport' => array(
                'name' => _t('PurchaseAccountSummaryReport.PERMISSION_VIEW', 'Allow view access right ({title})', '', array('title' => $this->title())),
                'category' => _t('PurchaseAccountSummaryReport.PERMISSIONS_CATEGORY', 'Report')
            )
        );
    }
}
